package guild

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/os/gmlock"
	"strconv"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/httpserver"
	"xr-game-server/dao/guilddao"
	"xr-game-server/dao/roledao"
	"xr-game-server/dto/guilddto"
	"xr-game-server/entity"
	"xr-game-server/errercode"
	"xr-game-server/module/name"
)

// CreateGuild 创建公会
func CreateGuild(ctx context.Context, req *guilddto.GuildCreateReq) (res string, err error) {
	// 获取当前用户角色
	roleId := httpserver.GetAuthId(ctx)
	//防止并发
	lockKey := fmt.Sprintf("lock:guild:create:%d", roleId)
	defer gmlock.Unlock(lockKey)
	if !gmlock.TryLock(lockKey) {
		return "", errercode.CreateCode(errercode.SysBuyLimit)
	}

	roleEntity := roledao.GetRoleByRole(roleId)
	if roleEntity.GuildId > common.Zero {
		return "", errercode.CreateCode(errercode.GuildExist)
	}

	// 检查公会名称是否已存在
	if existingGuild := name.ChkName(req.Name, entity.UnionNameType); !existingGuild {
		return "", errercode.CreateCode(errercode.NameRepeat)
	}

	// 创建公会
	guild := entity.NewGuild()
	guild.SetPresidentId(roleId)
	guild.SetName(req.Name)
	guild.SetDescription(req.Description)
	roleEntity.SetGuildId(guild.ID)

	// 创建公会成员（会长）
	member := entity.NewGuildMember(guild.ID, roleId)
	member.SetTitle(entity.GuildMemberTitlePresident)
	guilddao.AddMember(member)

	//推送工会创建成功
	return strconv.FormatUint(guild.ID, 10), nil
}
